package com.lagou.v4.container;

import com.lagou.mapper.Mapper;
import com.lagou.v4.LifeCycle;
import com.lagou.v4.coyote.Connector;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Kirito
 * @description:
 * @date 2020/05/02
 */
public class Service implements LifeCycle {

    private List<Connector> connectors;

    private Engine engine;

    private Element element;

    private Mapper mapper;

    public Mapper getMapper() {
        return mapper;
    }

    public Mapper initMapper() {
        this.mapper = new Mapper();
        mapper.setService(this);
        return mapper;
    }

    public Engine getEngine() {
        return engine;
    }

    public void setElement(Element element) {
        this.element = element;
    }

    @Override
    public void init() throws Exception {
        engine = initEngine();
        engine.init();

        initMapper().init();

        List<Connector> connectorList = getConnectors();
        for (Connector connector : connectorList) {
            connector.init();
        }
    }

    @Override
    public void start() throws Exception {
        //engine.start();
        for (Connector connector : connectors) {
            connector.start();
        }
    }

    private List<Connector> getConnectors() {
        List<Element> connectorElements = element.selectNodes("//Connector");
        connectors = new ArrayList<>(connectorElements.size());
        for (Element connectorElement : connectorElements) {
            String port = connectorElement.attributeValue("port");
            Connector connector = new Connector();
            connector.setPort(Integer.parseInt(port));
            connector.setService(this);
            connectors.add(connector);
        }
       return connectors;
    }

    private Engine initEngine() {
        Element engineElement = (Element) element.selectSingleNode("//Engine");
        Engine engine = new Engine();
        engine.setElement(engineElement);
        return engine;
    }
}
